import Vue from 'vue';
import Vuex from 'vuex';
import Cookies from 'js-cookie';
import {getLoginStatus, sendCode, login} from '../api/index'
Vue.use(Vuex);


/* ==========================================================
 *                          Vuex 状态管理
 *    简介：
 *        使用Vuex统一管理页面状态信息，主要包括以下信息：
 *        1、登录状态
 *        2、验证码发送时间-毫秒（考虑页面刷新、关闭等 倒计时依然有效）
 *        3、最后一次输入手机号码 - 用于自动填充
 *        4、当前播放的音频和状态
 * ========================================================== */

export default new Vuex.Store({
    state: {
        loginStatus: !+Cookies.get('loginStatus'),
        lastLoginPhone: Cookies.get('lastLoginPhone'),
        lastSendCodeTime: Cookies.get('lastSendCodeTime'),
        showLoginBox: false,
        showBuyConfirmBox: false,
        showListenBar: false,
        showBuyBar: false,
        playingAudioItem: undefined,
        isPlaying: false,
        networkStatus: true,
        _playingCourseAudios:[],
        channel: '',
    },
    getters: {
        islogin: state => {
            return state.loginStatus
        },
        lastLoginPhone: state => {
            return state.lastLoginPhone
        },
        lastSendCodeTime: state => {
            return state.lastSendCodeTime
        },
        showLoginBox: state => {
            return state.showLoginBox;
        },
        showBuyConfirmBox: state => {
          return state.showBuyConfirmBox;
        },
        showListenBar: state => {
            return state.showListenBar;
        },
        playingAudioItem: state => {
            return state.playingAudioItem;
        },
        isPlaying: state => {
            return state.isPlaying;
        },
        showBuyBar: state => {
          return state.showBuyBar;
        },
        networkStatus: state => {
          return state.networkStatus;
        },
        channel: state => {
          return state.channel;
        }
    },
    mutations: {
        loginSuccess(state) {
            console.log("loginSuccess");
            state.loginStatus = true;
            Cookies.set('loginStatus', 1, { expires: 7 });
            // clear lastSendCodeTime
            state.lastSendCodeTime = 0;
            Cookies.set('lastSendCodeTime', 0, { expires: 7 });
        },
        logout(state) {
            console.log("logout");
            state.loginStatus = false;
            Cookies.set('loginStatus', 0, { expires: 7 });
        },
        updateSendCodeTime(state) {
            var now = (new Date()).getTime();
            state.lastSendCodeTime = now;
            Cookies.set('lastSendCodeTime', now, { expires: 7 });
        },
        restoreSendCodeTime(state) {
          // clear lastSendCodeTime
          state.lastSendCodeTime = 0;
          Cookies.set('lastSendCodeTime', 0, { expires: 7 });
        },
        updateLastLoginPhone(state, payload) {
            state.lastLoginPhone = payload.phone;
            Cookies.set('lastLoginPhone', payload.phone, { expires: 365 });
        },
        toggleLoginBox(state) {
            console.log("toggleLoginBox");
            if(state.loginStatus == true){
                state.showLoginBox = false;
            }else{
                //统计 登录
                window._hmt.push(['_trackEvent', '登录', '弹窗登录框']);
                state.showLoginBox = !state.showLoginBox;
            }
        },
        toggleBuyConfirmBox(state) {
          console.log("toggleBuyConfirmBox");
          if(state.showBuyConfirmBox == true){
            state.showBuyConfirmBox = false;
          }else{
            //统计 订单
            window._hmt.push(['_trackEvent', '订单', '弹窗确认框']);
            state.showBuyConfirmBox = !state.showBuyConfirmBox;
          }
        },
        togglePlayAudioItem(state, payload) {
            if(state.playingAudioItem && state.playingAudioItem.id == payload.playingAudioItem.id){
                // 同一个音频，切换播放、暂停
                console.log("togglePlayAudioItem, change from isPlaying from " + state.isPlaying);
                state.isPlaying = !state.isPlaying;
            }else {
                // 不是同一个音频，开始播放新音频
                console.log("togglePlayAudioItem, switch playing");
                state.playingAudioItem = payload.playingAudioItem;
                state._playingCourseAudios = payload.playingCourseAudios;
                state.isPlaying = true;
            }
            // 不管怎么切换，都显示
            if(!state.showListenBar){
                state.showListenBar = true;
            }
        },
        finishPlayAudioItem(state) {
            if(!state.playingAudioItem) {
                return;
            }
            state.playingAudioItem.isPlaying = false;
            if(state._playingCourseAudios && state._playingCourseAudios.length > 0) {
                var len = state._playingCourseAudios.length;
                // 找到当前播放的音频
                var currentIndex = -1;
                for( var i=0; i< len; i++ ){
                    var item = state._playingCourseAudios[i];
                    if(item.id == state.playingAudioItem.id){
                        currentIndex = i;
                        break;
                    }
                }
                // 处理下一个音频
                if(currentIndex >=0 && currentIndex < len-1){
                    //判断下一个音频是否可以播放
                    var nextItem = state._playingCourseAudios[currentIndex + 1];
                    if(nextItem.free == 1 || nextItem.hasBuy == 1){
                        state.playingAudioItem = nextItem;
                        state.isPlaying = true;
                    }else{
                        state.isPlaying = false;
                    }
                }else if(currentIndex == len -1) {
                    //最后一个也播放完了 播放状态改为暂停
                    state.isPlaying = false;
                }else{
                    //在列表中没有找到这个音频，正常不可能出现
                    console.error("Can not found playingAudioItem");
                }
            }

        },
        toggleBuyBarItem(state, payload) {
            state.showBuyBar = payload.showBuyBar;
        },
        online (state) {
            state.networkStatus = 0;
        },
        offline (state) {
            state.networkStatus = 1;
        },
        setChannel (state, payload) {
          state.channel = payload.channel;
        }
    },
    actions: {
        refreshLoginStatus ({ commit }) {
            getLoginStatus().then(function(resp){
                console.log(resp);
                if(resp.code === 0){
                    commit('loginSuccess');
                    if(resp.data) {
                      commit('updateLastLoginPhone', {
                        phone: resp.data
                      });
                    }
                }else{
                    console.log(resp.msg);
                    commit('logout');
                }
            }).catch(function(err){
                console.log(err);
            });
        },
        sendCode ({ commit }, payload) {
            // 有网络的情况，立即开始倒计时
            if (window.navigator.onLine) {
              commit('updateSendCodeTime');
            }
            sendCode(payload.phone).then(function(resp){
                if(resp.code === 0){
                    // 统计 登陆--》发送验证码
                    window._hmt.push(['_trackEvent', '登录', '发送验证码']);
                    // 防止意外情况 判断网络不通，但是发送成功了
                    if (!window.navigator.onLine) {
                      commit('updateSendCodeTime');
                    }
                    commit('updateLastLoginPhone', payload);
                }else{
                    commit('restoreSendCodeTime');
                    console.log(resp);
                }
            }).catch(function(err){
                commit('restoreSendCodeTime');
                console.log("sendCode err:" + err);
            });
        },
        login ({ commit }, payload) {
            login(payload.phone, payload.code).then(function(resp){
                if(resp.code == 0){
                    //统计 登录
                    window._hmt.push(['_trackEvent', '登录', '登录成功']);
                    commit('updateLastLoginPhone', payload);
                    commit('loginSuccess');
                }else{
                    console.log(resp);
                }
            }).catch(function(err){
                console.log(err);
            });
        },
        loginSuccess({ commit }){
            commit("loginSuccess");
        },
        updateLastLoginPhone({commit}, payload){
            commit('updateLastLoginPhone', payload);
        },
        logout ({ commit }) {
            commit('logout');
        },
        toggleLoginBox ({ commit }) {
            commit('toggleLoginBox');
        },
        toggleBuyConfirmBox ({ commit }) {
          commit('toggleBuyConfirmBox');
        },
        togglePlayAudioItem ({ commit }, payload) {
            // 用户手动点击切换触发
            commit('togglePlayAudioItem', payload);
        },
        finishPlayAudioItem ({commit}) {
            // 播放器回调出发
            commit('finishPlayAudioItem');
        },
        toggleBuyBarItem ({ commit }, payload) {
          // 展示底部购买栏，通知其它组件需要上移动
          commit('toggleBuyBarItem', payload);
        },
        online ({ commit }) {
          commit('online');
        },
        offline ({ commit }) {
          commit('offline');
        },
        setChannel ({ commit }, payload) {
          // 修改渠道，从url里面获取
          commit('setChannel', payload);
        },
    }
})
